package com.huanuo.internetofthings.controller.user;

import com.huanuo.internetofthings.dto.user.LoginReqDto;
import com.huanuo.internetofthings.dto.user.RegisteReqDto;
import com.huanuo.internetofthings.service.user.UserFacadeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.unicorn.framework.base.base.AbstractBaseController;
import org.unicorn.framework.cache.cache.CacheService;
import org.unicorn.framework.core.ResponseDto;
import org.unicorn.framework.core.SysCode;
import org.unicorn.framework.core.exception.PendingException;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping({ "/user" })
@Api(value = "用户模块", tags = { "用户模块" })
public class UserController  extends AbstractBaseController {
	@Autowired
	private UserFacadeService userFacadeService;
	@Autowired
	private CacheService cacheService;
	@ApiOperation("新用户注册")
	@RequestMapping(value = { "/regist" }, method = { RequestMethod.POST })
	public ResponseDto<?> regist(@RequestBody RegisteReqDto registeReqDto) throws PendingException {
		try {
			return this.userFacadeService.register(registeReqDto);
		} catch (Exception e) {
			throw new PendingException(SysCode.SYS_FAIL);
		}
	}
	@ApiOperation("登录")
	@RequestMapping(value = { "/login" }, method = { RequestMethod.POST })
	public ResponseDto<?> login(@RequestBody LoginReqDto loginReqDto , HttpSession session) throws PendingException {
		validateCode(cacheService.get(session.getId(),"code"),loginReqDto.getCode());
		return this.userFacadeService.login(loginReqDto);
	}


	private  void  validateCode(Object code,String inputCode) throws PendingException{
		if(code==null){
			throw new PendingException(SysCode.SYS_FAIL,"验证码失效");
		}
		String codeStr=String.valueOf(code);
		if(!codeStr.equalsIgnoreCase(inputCode)){
			throw new PendingException(SysCode.SYS_FAIL,"验证码不正确");
		}
	}

	@ApiOperation("登出")
	@RequestMapping(value = { "/logout" }, method = { RequestMethod.GET })
	public ResponseDto<?> logout() throws PendingException {
		SecurityUtils.getSubject().logout();
		return new ResponseDto<>();
	}
	@ApiOperation("获取登录用户信息")
	@RequestMapping(value = { "/info" }, method = { RequestMethod.GET })
	public ResponseDto<?> info()throws PendingException {
		String userName = (String) SecurityUtils.getSubject().getPrincipal();
		if(StringUtils.isBlank(userName)){
			throw new PendingException(SysCode.SESSION_ERROR);
		}
		return userFacadeService.userInfo(userName);
	}

	@RequiresPermissions({ "user:detail:edit" })
	@RequestMapping(value = { "/edit/{id}" }, method = { RequestMethod.GET })
	public ResponseDto<?> edit(@PathVariable("id") Long id) {
		return new ResponseDto<>(id);
	}
}